
import $ from 'jquery'
import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope,scopeFactory} from 'lib/scopeFactory'


import apps from '../apis/apps'
import dashboards from '../apis/dashboards'



export default class MainScope extends Scope {
  constructor(){
    super();
    this.$state = {
      appList:{
        loading:true
      },
      dashboardList:{
        loading:true
      }
    }
    this.appList = apps()
    this.dashboardList = dashboards()
  }
  $rename_app(payload){
    var findedApp = _(this.$state.appList.data).findWhere({
      accountId:payload.id
    })
    findedApp.accountName = payload.name
    this.emit();
  }
  $delete_app(payload){
    this.$state.appList.data = _(this.$state.appList.data).filter(function(i){
      return i.accountId !== payload.id
    })
    this.emit()
  }
  $create_dashboard(payload){
    var _this = this
    window.location.reload()
  }
  $rename_dashboard(payload){
    var findedApp = _(this.$state.dashboardList.data).findWhere({
      id:payload.id
    })
    findedApp.name = payload.name
    this.emit()
  }
  $delete_dashboard(payload){
    this.$state.dashboardList.data = _(this.$state.dashboardList.data).filter(function(i){
      return i.id !== payload.id
    })
    this.emit()
  }
  $load(){
    var _this = this
    this.appList.fetch().then(function(data){
      _this.$state.appList = {
        data:data
      }
    },function(err){
      _this.$state.appList = {
        error:err
      }
    },function(params){
      _this.$state.appList = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
    this.dashboardList.fetch().then(function(data){
      _this.$state.dashboardList = {
        data:data
      }
    },function(err){
      _this.$state.dashboardList = {
        error:err
      }
    },function(params){
      _this.$state.dashboardList = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
  }
}
